<template>
  <div class="new">
    <!-- 内容组件 -->
    <content-template :formData="formData"
                      :searchData="searchData"
                      :tableData="tableData"
                      :getDatas ="getDatas"
                      @handleAdd="handleAdd"
                      @handleSubmit="handleSubmit">
    </content-template>
    <!-- 弹框组件 -->
    <dialog-template
            :options = "formData.options.hasAdd">
            <!-- 表单组件 -->
        <form-template
            :formData="formData"
            :options="formData.options.hasAdd"
            :formValidate="formData.formValidate"
            :rules="formData.ruleValidate"
            :list="formData.list"
            @handleSubmit="handleSubmit"
        >      
               
        <div slot="one">
           <div>
              <div>
                <h4 style="margin-bottom: 10px">音乐列表</h4>
                <Upload
                    :on-success="handleAudiosuccess"
                    :data="uploadClient"
                    name="files"
                    multiple
                    type="drag"
                    :on-progress ="handleprogress"
                    :action="$audioApi"
                    :show-upload-list="false">
                    <div style="padding: 20px 0">
                        <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                        <p>上传音频</p>
                    </div>
                </Upload>
                <Progress hide-info v-if="loadingStatus" :percent="uploadpercent" />
                <div  v-else v-for="(item,index) in fileList" :key="index" style="justify-content: space-between;width:100%;margin-top: 10px;display:flex;align-items:center" v-if="fileList.length > 0">
                  <audio style="width:85%"   controls :src="$imgUrl + item.url"></audio>
                  <Button type="primary" @click="delaudio(index)">删除</Button>
                </div>
              </div>
           </div>
           <div>
               <h4 style="margin-bottom: 10px">文章内容</h4>
               <!-- <wangeditor ref="editor" @getImg="getImg" @change="change" :isClear="isClear" :content="formData.options.hasAdd.formValidate.content"></wangeditor> -->
               <tinymce  ref="editor" v-model = "formData.options.hasAdd.formValidate.content"></tinymce>
           </div>
           <div v-if="formData.options.hasAdd.formValidate.type == 2">
              <p style="color: #cdcdcd">*建议上传尺寸344：195</p>
              <div>
                <h4 style="margin-bottom: 10px">视频</h4>
                <upload-video  ref="video"
                    @handleVideo="(value)=>{return handleVideo(value)}"  
                    :formStyle="formStyle" 
                    :videoUrl.sync = "formData.options.hasAdd.formValidate.content" 
                   >          
                </upload-video>
              </div>
              <div>
                <h4 style="margin: 20px 0">视频封面图</h4>
                <upload-img  ref="img"
                    @handleSuccess="(value)=>{return handleSuccess(value)}"  
                    :formStyle="formStyle" 
                    :imgUrl.sync = "formData.options.hasAdd.formValidate.image_url" 
                   >          
                </upload-img>
              </div>
           </div>
           <!-- <div v-if="formData.options.hasAdd.formValidate.type == 3">
             <Input v-model="formData.options.hasAdd.formValidate.content" placeholder="输入视频链接"></Input>
           </div> -->
        </div>

        </form-template>
    </dialog-template>
  </div>
</template>
<script>
import tinymce from '@/components/tinymce'
import uploadImg from '@/components/uploadImg'
import uploadVideo from '@/components/uploadVideo'
export default {
   data() {
    return {
      fileList:[],
      uploadpercent:'',
      loadingStatus:false,
      uploadClient : {},
      isClear: false,
      image_url:[],
      disabled: false,
      formStyle:{
        width:'200px',
        height:'200px',
        lineHeight:'200px'
      },
      formData:{
        index:'',
        options:{
          hasAdd:{  //需不需要新增按钮——为空时不显示
            modal: false,        //弹框状态
            isedit: false,       //是否是编辑状态
            title:'新闻' ,      //弹框标题
            width:800,           //弹框宽度
            class:"dialogClass", //弹框类名
            zIndex:100,          //弹框层级
            loading:true,        //弹框加载圈
            formValidate: {    //获取的表单数据
              news_title: '', 
              wechat_content:'',
              news_category_id:'',
              type:1,
              content:'',
              music_url:' ',
              image_url:''
            },
            ruleValidate: {    //验证表单信息
              
            },
          },
          hasSelect:{
            
            
          }       
        },
        list: [ //表单列表——进行一些表单操作
          // {
          //    type: 表单类型,
          //    label: 表单标题，
          //    prop:表单下标指引，要对应formValidate的字段
          //    formStyle:自定义表单的样式
          //    value:传入自定义数据
          // } 
          {
            type: "input",       
            prop: "news_title",
            label: "标题",
            placeholder:"",
            value:''
          },  
          {
            type: "input",       
            prop: "wechat_content",
            label: "朋友圈配文",
            inputtype:'textarea',
            placeholder:"",
            value:''
          },  
          {
            type: "select",       
            prop: "news_category_id",
            label: "分类",
            selectData:[],
            placeholder:"",
            value:''
          }, 
          {
            type: "custom", //自定义表单
            formArray:[
              {
                slot: "one", //插槽名
                prop: "content",
                label: "全部内容",
                placeholder:"",
                value:'',
              },
            ]      
          },    
        ],
      },
      searchData:{  
        searchValue: {  //搜索值
          name: '',
          keyword: '',
        },
        searchColumns: [ //搜索条件和搜索数量——不传则没有
          {
            key: 'name',
            label: "分类名称",
          },
          {
            key: 'keyword',
            label: "关键词",
          },
        ]
      },
      tableData:{  //表格数据及操作
        columns: [
          {
            title: '标题名称',
            key: 'news_title',
            align: 'center',
          },
          {
            title: '分类',
            key: 'name',
            align: 'center',
          },
          {
            title: '创建时间',
            key: 'create_time',
            align: 'center',
          },
          {
            title: '状态',
            align: 'center',
            render: (h, params) => {
              return h('i-switch', {
                  props: {
                    size:'large',
                    value: params.row.is_push == 2
                          ? false
                          : params.row.is_push == 1
                          ? true
                          : '未知'
                  },
                  scopedSlots:{
                    open:() => h('span', '推送'),
                    close:() => h('span', '不推送'),
                  },
                  on: {
                    'on-change': (value) => {
                        this.changepushStatus(params.index)
                    }
                  }
              })
            }
          },
          {
            title: '状态',
            align: 'center',
            render: (h, params) => {
              return h('i-switch', {
                  props: {
                    size:'large',
                    value: params.row.is_focus == 2
                          ? false
                          : params.row.is_focus == 1
                          ? true
                          : '未知'
                  },
                  scopedSlots:{
                    open:() => h('span', '关注推送'),
                    close:() => h('span', '关注不推送'),
                  },
                  on: {
                    'on-change': (value) => {
                        this.changefocusStatus(params.index)
                    }
                  }
              })
            }
          },
          {
            title: '状态',
            align: 'center',
            render: (h, params) => {
              return h('i-switch', {
                  props: {
                    size:'large',
                    value: params.row.status == 2
                          ? false
                          : params.row.status == 1
                          ? true
                          : '未知'
                  },
                  scopedSlots:{
                    open:() => h('span', '显示'),
                    close:() => h('span', '隐藏'),
                  },
                  on: {
                    'on-change': (value) => {
                        this.changeStatus(params.index)
                    }
                  }
              })
            }
          },
          {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 200,
            align: 'center',
            render: (h, params) => {
              let status = params.row.status
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.edit(params.index)
                    }
                  }
                }, '修改'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.deletes(params.index)
                    }
                  }
                }, '删除'),
              ]);
            }
          }
        ],
        data: [], //表格数据
        total:0,  //表格数据总量
        page:1,   //表格数据页码
        per_page:50,  //表格一页显示几条数据
        loading: true, //表格数据预加载
      }
    }
  },
  watch:{
     'formData.options.hasAdd.modal':{
         handler: function(val) {
           console.log("1")
           if(!this.formData.options.hasAdd.isedit){
              this.fileList = []
           }
         },
     }
  },
  created(){
    this.uploadClient = {
      session_id: this.Cookies.get('session')
    }
    this.getCate();
    console.log(window.location.href )
  },
  mounted() {
    this.getDatas();
  },
  methods: {
    handleprogress(event){
      this.uploadpercent = event.percent
      this.loadingStatus = true;
    },
    handleAudiosuccess(res,file){
        if (res.code == 200) {
            this.$Message.success('上传成功')
            this.loadingStatus = false;
            let value = ''
            let obj = {
               name: file.name,
               url : res.data
            }
            this.fileList.push(obj)
        }
    },
    delaudio(index){
      this.fileList.splice(index, 1)
    },
    change(val){
      this.formData.options.hasAdd.formValidate.content =  val 
    },
    getImg(val){
      console.log(val)
      this.image_url.push(val)
    },
    getDatas(){
      let params = {
        page:this.tableData.page,
        per_page:this.tableData.per_page,
        name:this.searchData.searchValue.name,
        keyword:this.searchData.searchValue.keyword,
      }
      this.$api.getnew(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.tableData.data = res.data.data
              this.tableData.total = res.data.total
              this.tableData.loading = false
          }
      })
    },
    getCate(){
      let params = {
        per_page:500,
      }
      this.$api.getnewscategory(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.formData.list[2].selectData = res.data.data.map(item=>{
                   item.category_name = item.name
                   item.id  = item.news_category_id
                   return item
              })
          }
      })
    },
    handleAdd (value) {
      this.isClear = !this.isClear
    },
    handleVideo(value) {
      this.$refs.video.videoUrl = value
      this.formData.options.hasAdd.formValidate.content =  value  // 上传视频的路径名
    },
    handleSuccess(value) {
      console.log(value)
      this.$refs.img.imgUrl = value
      this.formData.options.hasAdd.formValidate.image_url =  value  // 上传视频的路径名
    },
    changepushStatus(index){
      let is_push = "";
      let text = "";
      switch( this.tableData.data[index].is_push){
        case 1:
          text = "不推送"
          is_push = 2
          break;
        case 2:
          text = "推送"
          is_push = 1
          break;
        default:
          console.log('其他')
      };
      let params = {
        news_id: this.tableData.data[index].news_id,
        is_push: is_push
      }
      this.$api.is_topnews(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.$Message.success( text + '成功');
              this.getDatas();
            }
      })
    },
    changefocusStatus(index){
      let is_focus = "";
      let text = "";
      switch( this.tableData.data[index].is_focus){
        case 1:
          text = "关注不推送"
          is_focus = 2
          break;
        case 2:
          text = "关注推送"
          is_focus = 1
          break;
        default:
          console.log('其他')
      };
      let params = {
        news_id: this.tableData.data[index].news_id,
        is_focus: is_focus
      }
      this.$api.is_topnews(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.$Message.success( text + '成功');
              this.getDatas();
            }
      })
    },
    changeStatus(index){
      let status = "";
      let text = "";
      switch( this.tableData.data[index].status){
        case 1:
          text = "隐藏"
          status = 2
          break;
        case 2:
          text = "显示"
          status = 1
          break;
        default:
          console.log('其他')
      };
      let params = {
        news_id: this.tableData.data[index].news_id,
        status: status
      }
      this.$api.statusnew(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.$Message.success( text + '成功');
              this.getDatas();
            }
      })
    },
    edit(index){
      this.formData.index = index;
      this.getContent(index)
      this.formData.options.hasAdd.formValidate = {
        news_title: this.tableData.data[index].news_title,
        news_category_id:this.tableData.data[index].news_category_id,
        type:this.tableData.data[index].type,
        content:this.tableData.data[index].content,
        wechat_content:this.tableData.data[index].wechat_content,
      };
      if(this.tableData.data[index].music_url){
         this.fileList = JSON.parse(this.tableData.data[index].music_url)
      }
      if(this.tableData.data[index].video_image_url){
        this.formData.options.hasAdd.formValidate.image_url = this.tableData.data[index].video_image_url
      }
      this.formData.options.hasAdd.isedit = true
      this.formData.options.hasAdd.modal = true
    },
    getContent(index){
      let params = {
        news_id : this.tableData.data[index].news_id
      }
      this.$api.getnewdetail(params).then(res => {
        console.log(res);
        if (res.code == 200) {
          console.log(this.$refs.editor)
          if(res.data.type == 1){
            let content = res.data.content
            var tel = '<div class="lyyadvert"><a class="lyyadverturl" href="" target="_blank">广告位置<img  style="width:100%;height:195px" src="" /></a>'
            var regc = /<div.*?class="lyyadvert".*?>.*?<\/div>/ig; 
            this.$refs.editor.content  = content.replace(regc,tel);
          }else{
            this.formData.options.hasAdd.formValidate.content = res.data.content
            this.formData.options.hasAdd.formValidate.wechat_content = res.data.wechat_content,
            this.$refs.video.videoUrl = res.data.content
          }
        }
      })
    },
    deletes(index){
      this.$Modal.confirm({
        title: '提示',
        content: '确认删除该文章吗?',
        onOk: () => {
          let params = {
            news_id : this.tableData.data[index].news_id
          }
          this.$api.deletesnew(params).then(res => {
            console.log(res);
            if (res.code == 200) {
              this.$Message.success('删除成功');
              this.getDatas();
            }
          })
        }
      })
    },
    handleSubmit(value){
      // console.log(this.formData.options.hasAdd.formValidate.content)
      this.formData.options.hasAdd.formValidate.music_url = JSON.stringify(this.fileList)
      let content = this.formData.options.hasAdd.formValidate.content
      console.log(content)
      let type = 1
      if(content == '' && this.formData.options.hasAdd.formValidate.music_url !=''){
         type = 3
      }
      if ( this.formData.options.hasAdd.isedit == true) {
        let params = {
          news_id :  this.tableData.data[this.formData.index].news_id,
          news_title: this.formData.options.hasAdd.formValidate.news_title || '',
          news_category_id:this.formData.options.hasAdd.formValidate.news_category_id,
          type:type,
          content:content || '',
          music_url:this.formData.options.hasAdd.formValidate.music_url || '' ,
          wechat_content:this.formData.options.hasAdd.formValidate.wechat_content || '',
          video_image_url:this.formData.options.hasAdd.formValidate.image_url,
        }
        console.log(params)
        this.$api.editnew(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.formData.options.hasAdd.modal = false;
              this.$Message.success('修改成功');
              this.getDatas();
            }
        })
      }else{
        let params = {
          news_title: this.formData.options.hasAdd.formValidate.news_title || '',
          news_category_id:this.formData.options.hasAdd.formValidate.news_category_id,
          type:type,
          content:content || '',
          music_url:this.formData.options.hasAdd.formValidate.music_url || '',
          wechat_content:this.formData.options.hasAdd.formValidate.wechat_content || '',
          video_image_url:this.formData.options.hasAdd.formValidate.image_url,
        }
        console.log(params)
        this.$api.createnew(params)
          .then(res => {
            console.log(res);
            if (res.code == 200) {
              this.formData.options.hasAdd.modal = false;
              this.$Message.success('添加成功');
              this.getDatas();
            }
        })
      }
    },
  },
  components: {
     uploadVideo,
     tinymce,
     uploadImg
  }
}
</script>
<style lang="less" scoped>
    @import './index.less';
</style>
